﻿layui.use(['table', 'laypage', 'layer', 'util', 'laydate'], function () {
    var table = layui.table;
    var laypage = layui.laypage;
    var $ = layui.$;
    var icon = 0;
    var util = layui.util;
    var laydate = layui.laydate;
    var layer = layui.layer; // 添加layui弹出层模块

    $(function () {
        bindType();
        bindPrin();
    })

    // 渲染
    laydate.render({
        elem: '#storageDate'
    });
    //栋舍类型
    function bindType() {
        $.ajax({
            url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/CottageType', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                var enumData = res; // 直接使用返回的数据
                var select = $('#sheepBreed');
                $.each(enumData, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.text);
                    select.append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    };

    //负责人类型
    function bindPrin() {
        $.ajax({
            url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/PrincipalType', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                var enumData = res; // 直接使用返回的数据
                var select = $('#romm');
                $.each(enumData, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.text);
                    select.append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    };

    var type = "";
    var size = 15; // 每页显示条数
    //获取列表
    function getListData(page) {
        //获取查询条件
        var CottageType = $('#CottageType').val();
        var CottageName = $('#CottageName').val();
        var Principal = $('#Principal').val();
        //ajax后台交互
        $.ajax({
            url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/PageShowCottage',
            type: 'get',
            dataType: 'json',
            //参数
            data: {
                page: page,
                size: size,
                CottageType: CottageType,
                CottageName: CottageName,
                Principal: Principal,
            },
            success: function (res) {
                table.render({
                    //挂载的表格id
                    elem: '#ID-table-demo-setRowChecked',
                    cols: [[
                        { type: 'checkbox', width: 60, fixed: 'center', unresize: true, align: 'center' },
                        { field: 'number', type: 'numbers', title: '序号', width: 60, fixed: 'center', unresize: true, align: 'center', templet: '#zizeng' },
                        {
                            field: 'cottageType', title: '栋舍类型', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.cottageType == 1) return '公羊舍  ';
                                if (data.cottageType == 2) return '配种舍';
                                if (data.cottageType == 3) return '妊娠舍';
                                if (data.cottageType == 4) return '分娩舍  ';
                                if (data.cottageType == 5) return '青年舍';
                                if (data.cottageType == 6) return '育肥舍';
                                if (data.cottageType == 7) return '隔离舍  ';
                                if (data.cottageType == 8) return '混合舍  ';
                                if (data.cottageType == 9) return '哺乳舍';
                                if (data.cottageType == 10) return '后备舍';
                            }
                        },
                        { field: 'cottageName', title: '栋舍名称', width: 120, align: 'center' },
                        {
                            field: 'principal', title: '负责人', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.principal == 1) return '张三';
                                if (data.principal == 2) return '李四';
                                if (data.principal == 3) return '王五';
                            }
                        },
                        { field: 'cottageProduction', title: '生产人员', width: 120, align: 'center' },
                        {
                            field: 'cottageState', title: '状态', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.cottageState == true) return '禁用';
                                if (data.cottageState == false) return '使用';
                            },
                        },
                        { field: 'createBy', title: '创建人', width: 120, align: 'center' },
                        { field: 'createDate', title: '创建时间', width: 120, align: 'center' },
                        { field: 'updateBy', title: '修改人', width: 120, align: 'center' },
                        { field: 'updateDate', title: '修改时间', width: 120, align: 'center' },
                        { title: '操作', width: 200, align: 'center', templet: '#barDemo', fixed: 'right', unresize: true },

                    ]],
                    toolbar: '#demo-toolbar-setRowChecked',
                    initSort: { // 设置初始排序
                        field: 'experience', // 字段名
                        type: 'asc' // 倒序
                    },
                    data: res.data
                });

                //分页
                laypage.render({
                    //挂载的分页id
                    elem: 'pagesbox',
                    count: res.tatalCount,
                    limit: size,
                    curr: page,
                    layout: ['count', 'prev', 'page', 'next', 'skip'],
                    jump: function (obj, first) {
                        if (!first) {
                            getListData(obj.curr);
                        }
                    }
                });
            }
        });
    }
    $('#searchBtn').on('click', function () {
        getListData(1);
    });
    // 初始化加载数据
    $(function () {
        // 初始化加载数据
        getListData(1);
    })
    // 单删除
    function deleteData(cottageId) {
        $.ajax({
            url: `http://10.31.60.18:8000/AuthorizationSetRout/api/Cottage/DelCottage?cottageId=${cottageId}`,
            type: 'delete',
            success: function (res) {
                if (res > 0) {
                    layer.msg('删除成功');
                    location.href = "/Cottage/CottageList";
                } else {
                    layer.msg('删除失败');
                    getListData(1);
                }
            },
            error: function () {
                layer.msg('删除请求失败');
            }
        });
    }
    // 编辑删除按钮点击事件
    table.on('tool(ID-table-demo-setRowChecked)', function (obj) {
        var data = obj.data; // 获取当前行数据
        var cottageId = data.cottageId; // 获取当前行数据的唯一标识符
        if (obj.event == 'edit') {
            editData(data.cottageId); // 传递正确的数据项ID进行编辑操作
        }
        if (obj.event === 'add') {
            var url = `/Field/FieldAdd?cottageId=${cottageId}`;
            location.href = url; // 点击编辑按钮时跳转到修改页面
        }
        if (obj.event == 'delete') {
            layer.confirm('确定要删除吗？', function (index) {
                deleteData(data.cottageId); // 传递正确的数据项ID
                layer.close(index);
            });
        }
    });
    layui.config({
        base: '/mods/'
    });
    layui.use(['form'], function () {
        var obj = {};
        var form = layui.form;
        var layer = layui.layer;
        // 提交事件
        form.on('submit(save)', function (data) {
            if ($("[name='cottageId']").val() == "") {
                var field = data.field;
                obj.cottageType = field.cottageType;
                obj.cottageName = field.cottageName;
                obj.principal = field.principal;
                obj.cottageProduction = field.cottageProduction;
                obj.cottageState = field.cottageState;
                obj.cottageRemark = field.cottageRemark;
                console.log(field);
                $.post({
                    url: "http://10.31.60.18:8000/AuthorizationSetRout/api/Cottage/CreateCottage",
                    data: JSON.stringify(obj),
                    contentType: "application/json",
                    success: res => {
                        if (res > 0) {
                            layer.confirm('添加成功', {
                                btn: ['确定'] //按钮
                            }, function () {
                                location.href = "/Cottage/CottageList";
                            });
                        } else {
                            alert("添加失败");
                        }
                    }
                })
            } else {
                updateCottage();
            }
            return false; // 阻止默认 form 跳转
        });
    });
    // 重置按钮点击事件
    $('#closeBtn').on('click', function () {
        location.href = "/Cottage/CottageList";
    });
    //数据回显
    function editData(cottageId) {
        $.ajax({
            url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/FindIDCottage?CottageId=' + cottageId,
            type: 'get',
            contentType: 'application/json',
            success: function (res) {
                if (res != null) {
                    layer.open({
                        type: 1,
                        title: "修改新记录",
                        shift: 2,
                        closeBtn: false,
                        area: ['600px', '500px'],
                        shade: 0,
                        shadeClose: false,
                        content: $("#add-main"),
                        success: function (layero, index) {
                        }
                    });
                    $("[name='cottageId']").val(res.cottageId);
                    bindType();
                    $("#sheepBreed").val(res.cottageType);
                    $("#cottageName").val(res.cottageName);
                    $("#cottageProduction").val(res.cottageProduction);
                    $("#cottageRemark").val(res.cottageRemark);
                    bindPrin();
                    $("#romm").val(res.principal);
                } else {
                    layer.msg(res.msg, { icon: 5 });
                }
            },
            error: function (err) {
                // 处理请求错误
            }
        });
    }
    // 监听表单修改
    function updateCottage() {
        var formData = {
            cottageId: $("[name='cottageId']").val(), // 获取主键id
            cottageName: $("[name='cottageName']").val(),
            cottageProduction: $("[name='cottageProduction']").val(),
            cottageRemark: $("#cottageRemark").val(),
            cottageType: $("#sheepBreed").val(),
            principal: $("#romm").val(),
        };
        console.log(formData);
        $.ajax({
            url: 'http://10.31.60.18:8000/AuthorizationSetRout/api/Cottage/UpdCottage', // 替换为您的后端API接口地址
            type: 'put',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function (res) {
                if (res == 1) {
                    layer.msg("修改成功", { icon: 1 });
                    setTimeout(function () {
                        location.href = '/Cottage/CottageList'
                    }, 1000)
                } else {
                    layer.msg("修改失败", { icon: 2 });
                }
            },
            error: function () {
                layer.msg('网络错误，请稍后重试', { icon: 2 });
            }
        });
        return false; // 阻止表单跳转
    };
});
//新增栋舍
function onAddBtn() {
    var laydate = layui.laydate;
    // 渲染
    laydate.render({
        elem: '#storageDate'
    });

    layer.open({
        type: 1,
        title: "栋舍新增",
        closeBtn: false,
        shift: 12,
        area: ['600px', '500px'],
        shade: 0,
        shadeClose: false,
        content: $("#add-main"),
        success: function (layero, index) {
        }
    });
}